<?php

class GDGE_Auth_Adapter implements GDGE_Auth_Adapter_Interface
{	
	private $_config;
	
	private $_row = null;
	
	/**
	 * Setup adapter
	 * 
	 * @param GDGE_Auth_Config configuration for adapter
	 */
	public function __construct(GDGE_Auth_Config $config)
	{
		$this->_config = $config;
	}
	
	/**
	 * Performs authentication attempt
	 * @param string $username
	 * @param string $password
	 * @return Zend_Auth_Result
	 */
	public function authenticate($username, $password) {
		$config = $this->_config;
		$table = $config->getTable();
		$db = $table->getAdapter();
		$row = $table->fetchRow(
			$table->select()
				->where( $db->quoteIdentifier($config->getUsernameField()) .' = ?', $username)
		);
		
		if ($row == NULL) {
			return new GDGE_Auth_Result(GDGE_Auth_Result::FAILURE, -1);
		}
		$passField = $config->getPasswordField();
		$hash = $row->$passField;
		if (!GDGE_Util_PassHash::compareToHash($username, $password, $hash)) {
			return new GDGE_Auth_Result(GDGE_Auth_Result::FAILURE_CREDENTIAL_INVALID, $row->id);
		}
		$idField = $config->getIdField();
		$this->_row = $row;
		return new GDGE_Auth_Result(GDGE_Auth_Result::SUCCESS, $row->$idField);
	}
	
	public function validate($id)
	{
		return true; // TODO: add validation here
	}
	
	/**
	 * 
	 * Return user row from successful login
	 * @return Zend_Db_Table_Row
	 */
	public function getUserRow() {
		return $this->_row;
	}
}